const { chromium } = require("playwright");
const fs = require("fs");

async function savePageHtml(link, outputFile) {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto(link, { waitUntil: "networkidle" });

  // 获取主页面 HTML
  let html = await page.evaluate(() => document.documentElement.outerHTML);

  // 获取所有 iframe 内容
  const iframes = await page.frames();
  for (let i = 1; i < iframes.length; i++) {
    // 跳过主 frame（第一个）
    const frame = iframes[i];
    try {
      const frameHtml = await frame.evaluate(
        () => document.documentElement.outerHTML
      );
      html += `\n<!-- iframe content from ${frame.url()} -->\n`;
      html += frameHtml;
    } catch (error) {
      console.warn(`无法访问 iframe: ${frame.url()} - ${error.message}`);
    }
  }
  // 保存到文件
  // fs.writeFileSync(outputFile, html);

  console.log(`HTML 页面已保存到 ${outputFile}`);
  await browser.close();

  return html;
}

module.exports = {
  savePageHtml,
};
